#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "screen.h"
#include "world.h" /* world interface */

/* main function */
int main(int argc, char *argv[]) {
  /* initialize the window */
  if (screen_init(SCREEN_WIDTH,SCREEN_HEIGHT)) {
    fprintf(stderr, "Screen initialization failed.\n");
    exit(1);
  }
  screen_setcaption("My World!");
  
  /* state */
  WORLD_STATE state;
  init(&state);

#ifdef SHOW_FPS
  /* for FPS */ 
  u32 then = (u32)getticks();
  char msg[1024];
#endif
  u32 now = 0;
  
  /* game loop: render and update */
  while (state.quit == false) {
    now = (u32)getticks();
    state.frames++;
    
    /* update logic called before draw() */
    update(&state);
    
    /* call draw() to render the screen */
    draw(&state);

#ifdef SHOW_FPS
    /* calculate and show FPS */
    if (state.frames > SCREEN_FPS) {
      double fps = (double)state.frames * 1000 / (now - then);
      sprintf(msg, "[%2.1f]", fps);
      settextcolor(88, 88, 0);
      settextsize(18);
      outtextxy(msg, SCREEN_WIDTH-60, SCREEN_HEIGHT-28);
    }
#endif
    
    /* the above is rendering in memory,
       now put them on the screen all in once.*/
    screen_update();

    /* handles events, update status now */
    while (event_poll()) {
      /* the close window event */
      if (event_type(QUIT)) {
        state.quit = true;
      } else {
        /* keyboard events */
        keyboard_handler(&state);
        /* mouse events */
        mouse_handler(&state);
      }
    }
	/* FPS control, to render slower */
    if (getticks() - now < SCREEN_TICK_PER_FRAME) {
      //Wait remaining time
      delay(SCREEN_TICK_PER_FRAME + now - getticks());
    }
  }
  return 0;
}

